library(tidyverse)
library(estimatr)
library(haven)
library(scales)

setwd("~/Dropbox/GuessNyhanReifler/DART0023/PNAS/post_accept/replication files/US data")
setwd("../India data/Data/")

w1 <- read_dta("accuracy-fake-tips-congenial-ftf_data.dta") # FTF w1
w1$tips <- as_factor(w1$tips)

w2 <- read_dta("accuracy-fake-tips-congenial-online_data.dta") # online w1 (ignore var name)
w2$tips <- as_factor(w2$tips)

w1 <- w1 %>% mutate(type = case_when(dv %in% 7:12 ~ "Mainstream news",
                                     dv %in% 1:6 ~ "False news"))

w2 <- w2 %>% mutate(type = case_when(dv %in% 7:12 ~ "Mainstream news",
                                     dv %in% 1:6 ~ "False news"))

fig_1a <- w1 %>% split(.$type) %>%
  map(~ lm_robust(binary_accuracy ~ 0 + tips, clusters = caseid, data = .x)) %>% map_df(tidy, .id = "subgroup") %>%
  mutate(tips = str_replace(term, "tips", "")) %>% select(tips, subgroup, estimate, conf.low, conf.high)

fig_1b <- w2 %>% split(.$type) %>%
  map(~ lm_robust(binary_accuracy ~ 0 + tips, clusters = caseid, data = .x)) %>% map_df(tidy, .id = "subgroup") %>%
  mutate(tips = str_replace(term, "tips", "")) %>% select(tips, subgroup, estimate, conf.low, conf.high)

fig_1a$label <- "Face-to-face"
fig_1b$label <- "Online"
fig1 <- bind_rows(fig_1a, fig_1b)
fig1$subgroup <- as_factor(fig1$subgroup)
fig1$label <- as_factor(fig1$label)
fig1$label <- relevel(fig1$label, ref = "Online")

g <- ggplot(data = fig1, aes(y = estimate, x = subgroup, fill = tips)) + 
  facet_wrap(~ label, nrow = 1, ncol = 2, scales = "free") + 
  geom_bar(position = position_dodge(), stat = "identity", width = 0.7, color = "black") +
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), color = "black",
                width = .08, size = .2, position = position_dodge(0.7)) +
  scale_fill_manual("", values = c("lightgray", "darkgray"), label = c("Control", "Media literacy intervention")) +
  scale_y_continuous("", limits = c(0, 0.74), label = percent) + 
  xlab("") +  ylab("") +
  theme(legend.position = "bottom")

gnew <- g + theme(panel.grid.major = element_line(colour = "gray92"),
                  panel.grid.major.x = element_blank(),
                  panel.grid.minor = element_line(colour = "gray92"), 
                  panel.background = element_rect(fill = "white", color = "black"), 
                  panel.border = element_rect(colour = "black", fill = NA),
                  strip.background = element_rect(color = "black"),
                  #axis.text.x = element_text(angle = 20, hjust = 0.8),
                  legend.key = element_rect(fill = NA), 
                  legend.background = element_rect(fill = NA), 
                  axis.text.x = element_text(size = 12),
                  legend.text = element_text(size = 12),
                  strip.text = element_text(size = 12),
                  legend.direction = "horizontal") + labs(title = NULL)
gnew

#ggsave("../fig2_ggplot.pdf", gnew, width = 7, height = 4)

